﻿#include "LPScrollArea.h"

#include <QScrollBar>

struct LPScrollAreaPrivate
{
    LPScrollAreaPrivate():
       m_moveStart( false )
      ,m_continuousmove( false )
      ,m_mousePoint( 0,0 )
    {

    }
    bool m_moveStart;
    bool m_continuousmove;

    QPoint m_mousePoint;
};

LPScrollArea::LPScrollArea( QWidget * parent ):
    QScrollArea(parent),_P( new LPScrollAreaPrivate )
{
    installEventFilter(this);
    setLineWidth(0);
    setWidgetResizable(true);
    setFrameShape(QFrame::NoFrame);
    verticalScrollBar()->setVisible( false );
    horizontalScrollBar()->setVisible( false );
    verticalScrollBar()->setEnabled( false );
    setContentsMargins(0,0,0,0);
}

LPScrollArea::~LPScrollArea()
{

}

void LPScrollArea::wheelEvent(QWheelEvent *event)
{
    Q_UNUSED(event);
    if( event->delta() > 0 )
    {
        horizontalScrollBar()->setValue( horizontalScrollBar()->value() - 25 );
    }
    else
    {
        horizontalScrollBar()->setValue( horizontalScrollBar()->value() + 25 );
    }
}

bool LPScrollArea::eventFilter(QObject *Obj, QEvent *event)
{
    if( event->type() == QEvent::MouseMove )
    {
        QMouseEvent * mouseEvent = static_cast<QMouseEvent *>(event);
        if( mouseEvent->buttons() & Qt::LeftButton )
        {
            if( !_P->m_moveStart )
            {
                _P->m_moveStart = true;
                _P->m_continuousmove = false;
                _P->m_mousePoint = mouseEvent->globalPos();
            }
            else
            {
                QPoint point = mouseEvent->globalPos();
                int offsetX = point.x() - _P->m_mousePoint.x();
                if( !_P->m_continuousmove && (offsetX > -10 && offsetX < 10) )
                {
                    return  false;
                }
                _P->m_continuousmove = true;
                horizontalScrollBar()->setValue( horizontalScrollBar()->value() - offsetX );
                return  true;
            }
        }
    }
    else if( event->type() == QEvent::MouseButtonRelease )
    {
        _P->m_moveStart = false;
    }
    return QWidget::eventFilter(Obj,event);
}
